package org.bee.controller;

import jakarta.annotation.Resource;
import org.bee.ResultTool;
import org.bee.enums.IsDelete;
import org.bee.enums.ResultCode;
import org.bee.exception.ExceptionUtils;
import org.bee.id.UUIDUtils;
import org.bee.input.ElementInsertVo;
import org.bee.input.ElementSearchVo;
import org.bee.input.ElementUpdateVo;
import org.bee.model.Element;
import org.bee.model.result.Result;
import org.bee.output.ElementOut;
import org.bee.output.Menus;
import org.bee.secuirty.annotation.ApiAuth;
import org.bee.secuirty.context.CurrentUser;
import org.bee.service.ElementService;
import org.bee.service.RoleElementService;
import org.bee.transaction.TransUtils;
import org.bee.transaction.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * 页面元素管理
 */
@RestController
@RequestMapping("/element")
public class ElementController {
    Logger logger = LoggerFactory.getLogger(ElementController.class);

    @Resource
    ElementService elementService;

    @Resource
    private RoleElementService roleElementService;

    /**
     * 根据角色Id获取元素树
     * @param roleId 角色id
     * @return  元素树
     */
    @GetMapping("getElementsTree")
    @ApiAuth(value = "element.getElementsTree",description = "元素树")
    public Result getElementsTree(String roleId){
        Result result = ResultTool.success();
        List<Menus> menus = elementService.getMenusTree(null,roleId,true);
        result.setData(menus);
        return result;
    }

    /**
     * 查询元素
     * @param elementSearchVo 查询参数
     * @return  元素列表
     */
    @PostMapping("getElements")
    @ApiAuth(value = "element.getElements",description = "元素列表")
    public Result getElements(@RequestBody ElementSearchVo elementSearchVo){
        Result result = ResultTool.success();
        List<ElementOut> select = elementService.selectTree(elementSearchVo);
        result.setData(select);
        return result;
    }

    /**
     * 新增页面元素表
     * @param elementInsertVo 新增参数
     * @return 新增结果
     */
    @PostMapping("insert")
    @ApiAuth(value = "element.insert",description = "元素新增")
    public Result insert(@RequestBody ElementInsertVo elementInsertVo) {
        Result result = ResultTool.success();
        Transaction trans = null;
        try {
            Element element = new Element();
            BeanUtils.copyProperties(elementInsertVo, element);
            element.setElementId(UUIDUtils.simpleUuid());
            element.setCreateUserId(CurrentUser.getUser().getUserId());
            element.setCreateTime(new Date());
            element.setIsDeleted(IsDelete.FALSE.getCode());
            trans= TransUtils.getTrans();
            trans.begin();
            elementService.insert(element);
            trans.commit();
        } catch (Exception e) {
            TransUtils.rollback(trans);
            result = ResultTool.fail();
            logger.error(e.getMessage(), ExceptionUtils.getFullStackTrace(e));
            return result;
        }
        return result;
    }

    /**
     * 修改页面元素表
     * @param elementUpdateVo 修改参数
     * @return 修改结果
     */
    @PostMapping("update")
    @ApiAuth(value = "element.update",description = "元素修改")
    public Result update(@RequestBody ElementUpdateVo elementUpdateVo) {
        Result result = ResultTool.success();
        Transaction trans = null;
        try {
            Element element = new Element();
            BeanUtils.copyProperties(elementUpdateVo, element);
            element.setUpdateUserId(CurrentUser.getUser().getUserId());
            element.setUpdateTime(new Date());
            trans= TransUtils.getTrans();
            trans.begin();
            elementService.update(element);
            trans.commit();
        } catch (Exception e) {
            TransUtils.rollback(trans);
            result = ResultTool.fail();
            logger.error(e.getMessage(), ExceptionUtils.getFullStackTrace(e));
            return result;
        }
        return result;
    }

    /**
     * 删除页面元素表
     * @param id id
     * @return 删除结果
     */
    @DeleteMapping("delete")
    @ApiAuth(value = "element.delete",description = "元素删除")
    public Result delete(@RequestParam("id") String id) {
        Result result = ResultTool.success();
        Transaction trans = null;
        if (id == null|| id.isEmpty()) {
            result = ResultTool.fail(ResultCode.PARAM_NOT_COMPLETE);
            return result;
        }
        List<Element> elements = elementService.selectByPId(id);
        if (!elements.isEmpty()) {
            result = ResultTool.fail(ResultCode.DATA_IS_USED);
            result.setMsg("该元素下有子元素，无法删除");
            return result;
        }
        if(!roleElementService.selectByElementId(id).isEmpty()){
            result = ResultTool.fail(ResultCode.DATA_IS_USED);
            result.setMsg("该元素有角色在使用，无法删除");
            return result;
        }
        try {
            trans= TransUtils.getTrans();
            trans.begin();
            elementService.delete(id,false);
            trans.commit();
        } catch (Exception e) {
            TransUtils.rollback(trans);
            result = ResultTool.fail();
            logger.error(e.getMessage(), ExceptionUtils.getFullStackTrace(e));
            return result;
        }
        return result;
    }

    /**
     * 根据id查询元素
     * @param id id
     * @return 元素
     */
    @GetMapping("selectById")
    @ApiAuth(value = "element.selectById",description = "元素根据id查询")
    public Result getElementByCode(String id){
        Result result = ResultTool.success();
        if(id == null || id.isEmpty()){
            result = ResultTool.fail(ResultCode.PARAM_NOT_COMPLETE);
            result.setMsg("元素id不能为空");
            return result;
        }
        Element select = elementService.selectById(id);
        result.setData(select);
        return result;
    }
}
